package com.asset.dispoal.department.service.commom;

import com.asset.dispoal.department.domain.db.entity.SysDepartmentDo;
import com.asset.dispoal.department.domain.db.mapper.SysDepartmentMapper;
import com.asset.dispoal.department.dto.DepartmentRequest;
import com.asset.dispoal.department.dto.DepartmentResponse;
import com.asset.dispoal.department.service.converter.DepartmentConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.springboot.core.local.GlobalHeaderThreadLocal;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author qr
 * @date 2022/1/27$
 */
@Component
public class QueryDepartmentCommand implements BaseCommand<DepartmentRequest, Result> {

    @Autowired
    SysDepartmentMapper sysDepartmentMapper;

    @Override
    public Result<List<DepartmentResponse>> execute(DepartmentRequest request) {

        final SysDepartmentDo sysDepartmentDo = DepartmentConverter.INSTANCE.reqToDo(request);
        sysDepartmentDo.setPermission((String) GlobalHeaderThreadLocal.get().getExtraMap().get("permission"));

        final List<SysDepartmentDo> sysDepartmentDos = sysDepartmentMapper.queryAll(sysDepartmentDo.getCompanyId(), sysDepartmentDo.getPermission());

        final List<DepartmentResponse> departmentResponses = DepartmentConverter.INSTANCE.doToRes(sysDepartmentDos);

        final List<DepartmentResponse> collect = departmentResponses.stream().filter(item -> StringUtil.isBlank(item.getParentId())).collect(Collectors.toList());

        for (DepartmentResponse departmentResponse : collect) {
            recursion(departmentResponses, departmentResponse);
        }
        final List<DepartmentResponse> collect1 = departmentResponses.stream().filter(item -> StringUtil.isBlank(item.getParentId())).collect(Collectors.toList());
        return Result.ok(collect1);
    }


    private void recursion(List<DepartmentResponse> collect, DepartmentResponse departmentResponse) {
        for (DepartmentResponse response : collect) {
            if (departmentResponse.getId().equals(response.getParentId())) {
                departmentResponse.getResponseList().add(response);
                recursion(collect, response);
            }
        }
    }
}
